<template>
  <div class="course-management-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>课程名称：</span>
        <el-input
          v-model="courseName"
          placeholder="请输入课程名称"
          style="width: 300px; margin-left: 10px;"
        ></el-input>
      </div>
      <!-- 章节-->
      <div class="chapter-list">
        <div v-for="(chapter, chapterIndex) in filteredChapters" :key="chapter.id" class="chapter-item">
          <div class="chapter-header">
            <el-input
              v-model="chapter.name"
              placeholder="请输入章节名称"
              style="width: 300px;"
            ></el-input>
          </div>
          <!--添加课件-->
          <div class="material-list">
            <div v-for="(courseware, cwIndex) in getCoursewares(chapter.id)" :key="courseware.id" class="material-item">
              <div class="material-content">
                <div class="material-type">
                  <span>课件{{ cwIndex + 1 }}：</span>
                </div>
                <div class="material-inputs">
                  <el-input
                    v-model="courseware.name"
                    placeholder="请输入课件名称"
                    style="width: 300px; margin-bottom: 10px;"
                  ></el-input>
                  <div class="upload-area">
                    <el-upload
                      class="upload-demo"
                      ref="upload"
                      action="#"
                      :on-change="(file, fileList) => handleFileChange(file, fileList, courseware.id)"
                      :on-success="handleUploadSuccess"
                      :show-file-list="true"
                      :file-list = "courseware.videoUrl"
                      :auto-upload = "false"
                      :limit ="1"
                    >
                      <el-button size="small" type="primary">上传课件视频</el-button>
                    </el-upload>
                  </div>

                  <el-checkbox v-model="courseware.fortry" true-label="1" false-label="0" style="margin-top: 10px;">
                    开启试学（即用户购买前也能学习）
                  </el-checkbox>
                </div>

                <div class="material-actions">
                  <el-button
                    size="small"
                    @click="moveDownCourseware(chapter.id, cwIndex)"
                    :disabled="cwIndex === getCoursewares(chapter.id).length - 1"
                  >
                    下移
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="removeCourseware(chapter.id, cwIndex)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>

            <el-button
              type="text"
              icon="el-icon-plus"
              @click="addCourseware(chapter.id)"
              class="add-material-btn"
            >
              添加课件
            </el-button>
          </div>
        </div>

        <el-button
          type="text"
          icon="el-icon-plus"
          @click="addChapter"
          class="add-chapter-btn"
        >
          添加章节
        </el-button>
      </div>

      <div class="action-buttons">
        <el-button type="primary" @click="saveAndPublish">保存</el-button>
<!--        <el-button @click="saveOnly">仅保存</el-button>-->
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import {createbckcb, savebckcb, fileuploadres, querybckcb, updatecbstate} from "../../api/InstitutionApi";

export default {
  data() {
    return {
      courseName: '', ///课程名称
      oldchapters: [
        {
          name: '', ///章节名称
          materials: [
            {
              name: '', ////课件名称
              videoUrl: '', ////课件视频地址
              tryLearn: false   ////是否试学
            }
          ]
        }
      ],
      // type:类型，0章节，1课件
      // id:独立，可以使用type+index，就是章节为,001,002，003，课件为101,102,103
      // pid：服节点id，章节的pid就为0，课件的pid为章节的id
      // resuri：图片的索引
      // fortry：试读，0不试读，1试读
      // index：索引顺序
      chapters:[
        {"name":"章节1","type":"0","id":"11","pid":"0",
          "videoUrl":[],"resuri":"","fortry":"0","index":"1"},
        {"name":"课件1","type":"1","id":"111","pid":"11",
          "videoUrl":[],"resuri":"","fortry":"0","index":"1"},
        {"name":"课件2","type":"1","id":"112","pid":"11",
          "videoUrl":[],"resuri":"","fortry":"0","index":"2"},

        {"name":"章节2","type":"0","id":"12","pid":"0",
          "videoUrl":[],"resuri":"","fortry":"0","index":"2"},
        {"name":"课件1","type":"1","id":"121","pid":"12",
          "videoUrl":[],"resuri":"","fortry":"0","index":"1"},
        {"name":"课件2","type":"1","id":"122","pid":"12",
          "videoUrl":[],"resuri":"","fortry":"0","index":"2"},
      ],  ////主要用于展现时用，而且viedeoUrl:[]
      saveChapters: [], ///跟chapters一样，主要用于保存时用,而：videoUrl:"" 主要用于存储视频返回的code
      kcCode: '', ///课程code
      kcName: '', ///课程名称
    //获取课程表时临时保存
      tmpEditChapters:[], ///保存服务端获取回来的全部内容
      tmpNodeChapters: [],  ///先保存type=0根节点,再往根节后点后面添加课件项
    }
  },
  computed: {
    // 获取所有章节（type为0的项）,并且升序
    // 如果 index 是字符串（如 "1"、"2"），仍能正确排序，因为减法操作会隐式转换为数字,
    filteredChapters() {
      return this.chapters.filter(item => item.type === '0').sort((a, b) => a.index - b.index);
    }
  },
  created() {
    this.kcCode = this.$route.query.kccode;
    this.courseName = this.$route.query.kcname;
    this.editCourseTable()
  },
  methods: {
    // 获取课程表，有则编辑，否则添加
    editCourseTable() {
      querybckcb({
        "bccode": this.kcCode, ////#课程code
      }).then(res => {
        console.log('gettable:', res)
        if(res.data.data.base_info.length !== 0) {
          this.tmpEditChapters = []
          this.tmpEditChapters = res.data.data.base_info
          this.chanageEditChapter()
        }
      }).catch(err =>{
        this.$message.success('加载不成功！');
      })
    },
    // 当获取课程表时的处理,开始
    chanageEditChapter() {
      this.chapters = []
      // let tmpNode = this.tmpNodeChapters.filter(item => item.bckcb_res_type === 0)
      let tmpNode = this.tmpEditChapters
      for(let i=0;i<tmpNode.length;i++){
        this.chapters.push({
          "name": tmpNode[i].bckcb_res_name,
          "type": String(tmpNode[i].bckcb_res_type),
          "id": tmpNode[i].bckcb_code,
          "pid": tmpNode[i].bckcb_parentcode,
          "videoUrl": this.chanageVideo(tmpNode[i].bckcb_res_uri),
          "resuri": tmpNode[i].bckcb_res_uri[0].imguri,
          "fortry": String(tmpNode[i].bckcb_res_fortry),
          "index": String(tmpNode[i].bckcb_res_orderindex)
        })
      }
      console.log('转化后的chapter:',this.chapters)
    },
    // 视频数组处理
    chanageVideo(videoArray) {

      let laterVideo = []
      for(let i=0;i<videoArray.length;i++){
        if(videoArray[i].url !== "") {
          laterVideo.push({
            name: videoArray[i].imgname,
            url: videoArray[i].url
          })
        } else {
          return laterVideo = []
        }
      }
      return laterVideo
    },

    // 当获取课程表时的处理,结束

    // 获取某个章节下的所有课件
    getCoursewares(chapterId) {
      return this.chapters
        .filter(item => item.type === '1' && item.pid === chapterId)
        .sort((a, b) => a.index - b.index);
    },
    // 安全获取最大id（数字类型）
     getMaxId(chapters) {
      const ids = chapters
        .map(item => parseInt(item.id))
        .filter(id => !isNaN(id));
      return ids.length > 0 ? Math.max(...ids) : null;
    },

    // 添加章节
    addChapter() {
      // this.chapters.push({
      //   name: '',
      //   materials: [
      //     {
      //       name: '',
      //       videoUrl: '',
      //       tryLearn: false
      //     }
      //   ]
      // });
      // const newId = Date.now().toString();
      // console.log('添加章节：',this.filteredChapters.length)
      // 获取最大的课程id值
      let  maxId = this.getMaxId(this.filteredChapters);
      this.chapters.push({
        name: '',
        type: '0',
        id: String(parseInt(maxId)+1),
        pid: '0',
        videoUrl: [],
        fortry: '0',
        index: this.filteredChapters.length + 1
      });
    },
    // 添加课件
    addCourseware(chapterId) {
      // this.chapters[chapterIndex].materials.push({
      //   name: '',
      //   videoUrl: '',
      //   tryLearn: false
      // });
      // 根据ID过滤出当前id下的数组对象
      let coursewares = this.getCoursewares(chapterId);
      this.chapters.push({
        name: '',
        type: '1',
        id: String(chapterId)+String(coursewares.length+1),  ////第一个（id+index），后面index+1
        pid: chapterId,  ///父章节的id
        videoUrl: '',
        fortry: '0',
        index: coursewares.length + 1
      });
      console.log('添加课件-1 ：',this.chapters);
    },
    // 删除课件
    removeCourseware(chapterId, index) {
      const courseware = this.getCoursewares(chapterId)[index];
      this.chapters = this.chapters.filter(item => item.id !== courseware.id);
    },
    // removeMaterial(chapterIndex, materialIndex) {
    //   this.chapters[chapterIndex].materials.splice(materialIndex, 1);
    // },
    // 下移
    moveDownCourseware(chapterId, index) {
      const coursewares = this.getCoursewares(chapterId);
      if (index < coursewares.length - 1) {
        const current = coursewares[index];
        const next = coursewares[index + 1];
        // 交换index
        [current.index, next.index] = [next.index, current.index];
      }
    },

    // moveMaterialDown(chapterIndex, materialIndex) {
    //   if (materialIndex < this.chapters[chapterIndex].materials.length - 1) {
    //     const temp = this.chapters[chapterIndex].materials[materialIndex];
    //     this.$set(this.chapters[chapterIndex].materials, materialIndex, this.chapters[chapterIndex].materials[materialIndex + 1]);
    //     this.$set(this.chapters[chapterIndex].materials, materialIndex + 1, temp);
    //   }
    // },

    handleUploadSuccess(response, file, fileList) {
      console.log('up:',response, file, fileList);
      // 处理上传成功的逻辑，将返回的视频URL保存到对应的课件中
      // 需要根据实际情况实现
    },

    // 当文件变化时
    async handleFileChange(file, fileList, chapterid) {
      // this.fileListurl = fileList;
      // console.log('onchange-1:',URL.createObjectURL(file.raw),chapterid);
      // 构建文件信息对象
      // const fileInfo = {
      //   name: file.name,
      //   size: file.size,
      //   // type: file.raw?.type || 'video/mp4',
      //   tempPath: tempPath, // 临时路径
      //   raw: file.raw,      // 原始文件对象
      //   status: 'ready'     // 自定义状态
      // };

      // 更新fileList
      // this.fileList = fileList.map(f => {
      //   if (f.uid === file.uid) {
      //     return { ...f, ...fileInfo };
      //   }
      //   return f;
      // });

      // 1.当文件变化时，需要首先将临时文件与文件名称存储入相应的数组对象中
      // 获取文件的临时路径（不同浏览器兼容处理）
      const tempPath = file.url || URL.createObjectURL(file.raw);
      // 调用存储函数
      const newVideo = {
        name: file.name,
        url: tempPath
      };

      let formData = new FormData();
      // const fileupdown = this.fileList[0].raw; // 获取原始文件对象
      const fileupdown = file.raw
      // 文件形式上传
      formData.append('restype', '10'); // 资源类型：10=视频
      formData.append('resfile', fileupdown);
      console.log('当前文件列表:', formData);
      // 以文件形式上传视频到服务端
      this.fileuploadres(formData,chapterid, newVideo)

    },

    // 以文件形式上传视频
    fileuploadres(formData,chapterid, newVideo) {
      // 显示加载中
      const loading = this.$loading({
        lock: true,
        text: '视频上传中', // 初始文本
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      fileuploadres(formData,{
        headers:{
          'Content-Type': 'multipart/form-data' // 必须设置
        },
        onUploadProgress: (progressEvent) => {
          // 上传进度显示
          const percent = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          // loading.setText(`视频上传中 ${percent}%`);
          loading.setText(`视频上传中`);
        }
      }).then(res => {
        // 上传成功
        loading.close();
        this.$message.success('视频上传成功');
        console.log('video:',res )
        let resCode = res.data.res_code;
        this.$set(newVideo, 'videocode', resCode);
        // 2.向id为chapterid的项目添加视频路径与文件名
        this.addVideoUrlToChapter(chapterid, newVideo);
      })
    },

    // 2.向id为chapterid的项目添加视频路径与文件名
    addVideoUrlToChapter(targetId, newVideo) {
      // 深拷贝chapters数组以避免直接修改（Vue2响应式要求）
      const updatedChapters = JSON.parse(JSON.stringify(this.chapters));
      // 查找目标对象
      const targetItem = updatedChapters.find(item => item.id === targetId);

      if (targetItem) {
        // 确保videoUrl是数组
        if (!Array.isArray(targetItem.videoUrl)) {
          targetItem.videoUrl = [];
        }
        // 添加新记录视频路径和code
        targetItem.videoUrl.push({
          name: newVideo.name,
          url: newVideo.url,
        });
        targetItem.resuri = newVideo.videocode;

        // 更新chapters（确保响应式）
        this.chapters = updatedChapters;

        console.log(`已向ID ${targetId} 添加视频记录`,this.chapters);
        return true;
      } else {
        console.warn(`未找到ID为 ${targetId} 的项目`);
        return false;
      }
    },
    // 删除数组内指定字段
    doingArray(doArray) {
      // 创建新的不包含 videoUrl 的对象数组
      this.saveChapters = doArray.map(item => {
        const { videoUrl, ...rest } = item; // 使用解构排除 videoUrl
        return rest;
      });

      // // 替换整个数组（也会触发响应式更新）
      // this.saveChapters = newChapters;
    },


    // 保存并发布课程表
    saveAndPublish() {
      // 先将chapter深度复制给另一个
      const tmpChapters = JSON.parse(JSON.stringify(this.chapters));
      this.doingArray(tmpChapters)
      // 仅保存逻辑
      createbckcb({
        "bccode": this.kcCode,///#课程code
        "bckcb":{ chapters: this.saveChapters } ///#课程表信息
      }).then(res => {
        console.log('保存并发布：',res)
        this.$router.push({
          path: '/onlineCourse/index',
          query: ''
        });
      })
      console.log('保存查看地：', this.chapters,this.saveChapters)
      // this.$message.success('课程已保存');
      // 保存并发布逻辑
      // this.$message.success('课程已保存并发布');
    },


    // 仅保存课程表
    saveOnly() {
      // 仅保存逻辑
      savebckcb({
        "bccode": this.kcCode,///#课程code
        "bckcb":{ chapters: this.chapters } ///#课程表信息
      }).then(res => {
        console.log('仅保存：',res)

      })
      console.log('保存查看地：', this.chapters)
      // this.$message.success('课程已保存');
    },

    cancel() {
      this.$confirm('确定要取消编辑吗？所有未保存的更改将丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.info('已取消编辑');
        // 这里可以添加路由跳转或其他取消逻辑
        this.$router.push({
          path: '/onlineCourse/index',
          query: ''
        });
      });
    }
  }
}
</script>

<style scoped>
.course-management-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.chapter-list {
  margin-bottom: 20px;
}

.chapter-item {
  margin-bottom: 30px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.chapter-header {
  margin-bottom: 15px;
}

.material-list {
  margin-left: 30px;
}

.material-item {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.material-content {
  display: flex;
  justify-content: space-between;
}

.material-inputs {
  flex: 1;
}

.material-actions {
  margin-left: 20px;
  display: flex;
  flex-direction: column;
}

.upload-area {
  margin-bottom: 10px;
}

.add-material-btn, .add-chapter-btn {
  color: #409EFF;
  padding-left: 0;
}

.add-chapter-btn {
  margin-top: 20px;
}

.action-buttons {
  margin-top: 20px;
  text-align: center;
}
</style>
